<template>
    <div class="iotdeviceDetails-page">
        <el-row :gutter="20">
            <el-col :span="6">设备编码：{{ fromInfo.deviceCode }}</el-col>
            <el-col :span="6">安装位置：{{ fromInfo.address }}</el-col>
            <el-col :span="6">所属机构：{{ fromInfo.deptName }}</el-col>
            <el-col :span="6">运行状态：{{ fromInfo.switchStatus === 3 ? '高' :
                fromInfo.switchStatus === 2 ? '中' :
                    fromInfo.switchStatus === 1 ? '低' :
                        fromInfo.switchStatus === 0 ? '关' : '关'
            }}</el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="6">滤网使用时长：{{ fromInfo.useTime }}小时</el-col>
            <el-col :span="6">滤网剩余时长：{{ fromInfo.remainingTime }}小时</el-col>
            <el-col :span="6">设备使用时长：{{ fromInfo.runTime }}小时</el-col>
        </el-row>
        <div class="models" v-if="fromInfo.attributeVOS">
            <div v-for="(item, index) of fromInfo.attributeVOS" :class="[activeIndex === index ? 'active' : '', 'model']"
                @click="getLineInfo(index)">
                <div class="title">{{ item.attributeName }}（{{ item.specUnitName }}）</div>
                <div>{{ item.value }}</div>
            </div>
        </div>
        <div class="time">
            <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To"
                start-placeholder="Start date" end-placeholder="End date" @visible-change="visibleChange" />
        </div>
        <div class="chartDom" ref="chartDom"></div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts';
import { getDetail, getDiscountCurve } from "@/api/desk/iotdevice";

const definePropsInfo = defineProps({
    fromItem: {
        type: Object,
        default: () => (null)
    }
})
// 设备数据
const fromInfo = ref()
// 时间范围
const end = new Date()
const start = new Date()
start.setMonth(start.getMonth() - 1)

const value2 = ref([start, end])
const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)
            return [start, end]
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            return [start, end]
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 3)
            return [start, end]
        },
    },
]
const visibleChange = (e) => {
    if (!e) {
        getLineInfo(activeIndex.value)
    }
}
// 当前被选中的模块是哪一个
const activeIndex = ref(0)
const chartDom = ref(null);
const chartInstance = ref(null);
// 折线图数据
const xAxis = ref([])
const yAxis = ref([])

onMounted(() => {
    getDeviceDetail()
});

// 获取设备详情
const getDeviceDetail = () => {
    getDetail({
        id: definePropsInfo.fromItem.id
    }).then((res) => {
        fromInfo.value = res.data?.data
        getLineInfo()
    })
}

// 获取折线图
const getLineInfo = (index = 0) => {
    activeIndex.value = index
    if (!fromInfo.value.attributeVOS || !fromInfo.value.attributeVOS.length) {
        return
    }
    xAxis.value = []
    yAxis.value = []
    getDiscountCurve({
        deviceId: definePropsInfo.fromItem.id,
        attributeCode: fromInfo.value.attributeVOS[activeIndex.value]['attributeCode'],
        startTime: value2.value ? formatDateTime(value2.value[0]) : '',
        endTime: value2.value ? formatDateTime(value2.value[1]) : ''
    }).then((res) => {
        if (res.data?.data) {
            res.data?.data.map((value) => {
                xAxis.value.push(value.createTime)
                yAxis.value.push(value.attributeCodeValue)
            })
            getChart()
        }
    })
}

// 画折线图
const getChart = () => {
    if (!chartInstance.value) {
        chartInstance.value = echarts.init(chartDom.value);
    }
    const option = {
        title: {
            text: `${fromInfo.value.attributeVOS[activeIndex.value]['attributeName']}趋势分析`,
            left: 'center',
            textStyle: {
                fontSize: 18,
                fontWeight: 'bold'
            }
        },
        tooltip: { trigger: 'axis' },
        xAxis: {
            type: 'category',
            axisLabel: {
                rotate: 40,
                fontSize: 12,
                margin: 15  // 标签与轴线距离
            },
            data: xAxis.value
        },
        yAxis: { type: 'value' },
        series: [
            { data: yAxis.value, type: 'line' }
        ],
        dataZoom: [{
            type: 'slider',
            xAxisIndex: 0,
            start: 0,
            end: 100,
            filterMode: 'filter',
            show: false,  // 关键配置
        }, {
            type: 'inside',
            xAxisIndex: 0
        }]
    };
    chartInstance.value.setOption(option);
}

const formatDateTime = (date: any): string => {
    const padZero = (num: number): string =>
        (num < 10 ? '0' + num : num.toString());

    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1);
    const day = padZero(date.getDate());
    const hours = padZero(date.getHours());
    const minutes = padZero(date.getMinutes());
    const seconds = padZero(date.getSeconds());

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


onUnmounted(() => {
    if (chartInstance.value) chartInstance.value.dispose();
});

</script>

<style lang="scss">
.iotdeviceDetails-page {
    padding: 20px;

    .time {
        margin-top: 30px;
        text-align: right;
    }

    .chartDom {
        margin: 30px auto 0;
        width: 1000px;
        height: 400px;
    }

    .models {
        margin: 30px auto 0;
        width: 80%;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .model {
            margin: 0 auto;
            border-radius: 4px;
            border: 1px solid #eeeeee;
            padding: 10px;
            text-align: center;
            width: 150px;
            flex-shrink: 0;
            min-width: fit-content;

            div {
                font-size: 35px;
                font-weight: bold;

                &.title {
                    font-size: 18px;
                    font-weight: 500;
                    margin-bottom: 20px;
                }
            }

            &:hover {
                background: #eeeeee;
            }

            &.active {
                background: #eeeeee;
            }
        }
    }
}
</style>
